<script lang="ts" setup>
import {computed, ref} from 'vue'
import {useBrowsingHistoryStore} from "@/stores/browsingHistory"
import {formatTimeDifference} from "@/utils/time"
import {onPullDownRefresh, onReachBottom, onShow} from "@dcloudio/uni-app";
import {IMessage} from "@/components/aw-message/message";

const {safeAreaInsets} = uni.getSystemInfoSync()

const browsingHistoryStore = useBrowsingHistoryStore()
onPullDownRefresh(() => {
  uni.stopPullDownRefresh()
})

// 时间渲染
const initTime = () => {
  for (let i = 0; i < browsingHistoryStore.browsingHistory.length; i++) {
    browsingHistoryStore.browsingHistory[i].timeDesc = formatTimeDifference(browsingHistoryStore.browsingHistory[i].time, new Date().getTime())
  }
}
onShow(() => initTime())
const checkList = ref<boolean[]>([])
const isShowCheck = ref(false)
checkList.value = new Array(browsingHistoryStore.browsingHistory.length).fill(false)
// 计算是否全选
const isCheckedAll = computed(() => {
  return checkList.value?.every(item => item)
})
/**
 * 长按
 * @param index 长按目标
 */
const onLongPress = (index: number) => {
  isShowCheck.value = !isShowCheck.value
  checkList.value![index] = true
}
//删除
const hPopup = ref()
const onDeleteHistory = () => {
  if (checkList.value?.every(item => !item)) {
    return uni.showToast({title: "请选择要删除的记录", icon: "none"})
  }
  hPopup.value.open()
}
const onConfirmDelete = () => {
  IMessage({
    type: "success",
    content: "删除成功",
    showIcon: true
  })
  if (isCheckedAll.value) {
    return browsingHistoryStore.clearAllBrowsingHistory()
  }
  const ids = checkList.value?.map((item, index) => {
    if (item) {
      return browsingHistoryStore.browsingHistory[index].id
    }
  })
  if (ids?.length === 0) {
    return
  }
  browsingHistoryStore.clearBrowsingHistory(ids as string[])
}

/**
 * 点击图片
 * @param id 动物id
 */
const onClickImg = (id: string) => {
  uni.navigateTo({url: `/subPkg/detail/detail?id=${id}`})
}
/**
 * 点击右侧区域
 * @param id
 * @param index
 */
const onClickRight = (id: string, index: number) => {
  if (!isShowCheck.value) {
    return uni.navigateTo({url: `/subPkg/detail/detail?id=${id}`})
  }
  checkList.value![index] = !checkList.value![index]
}

/**
 * TODO
 */
const onFilterHistory = () => {
  uni.showToast({title: "这个功能以后再用吧ヾ(≧▽≦*)o", icon: "none"})
}

/**
 * 点击更多
 */
const onClickMore = (id: string) => {
  uni.showActionSheet({
    itemList: ['删除该历史'],
    itemColor: '#39c5bb',
    success: function (res) {
      if (res.tapIndex === 0) {
        browsingHistoryStore.clearBrowsingHistory([id])
        uni.showToast({title: '已移除', icon: 'none'})
      }
    },
    fail: function (res) {
    }
  });
}
const pageSize = ref(20)
onReachBottom(() => {
  pageSize.value += 20
})
</script>

<template>
  <view :style="{ paddingBottom: '60px'}" class="history">
    <view style="position:fixed;top: 0;left: 0;right: 0;z-index: 999;">
      <aw-nav-second :title="'历史浏览'">
        <template v-slot:nav-right>
          <!-- #ifndef MP-WEIXIN -->
          <text class="cuIcon-search line-awGreen margin-lr-xs" style="font-size: 48rpx"
                @click="onFilterHistory"></text>
          <!-- #endif -->
          <text class="text-df text-gray margin-left-xl" @click="isShowCheck = !isShowCheck">{{
              isShowCheck ? '取消' : '管理'
            }}
          </text>
        </template>
      </aw-nav-second>
    </view>
    <view :scroll-y="true" class="history-list" style="padding-bottom: 100rpx;">
      <view v-for="(item, index) in browsingHistoryStore.browsingHistory.slice(0,pageSize)" :key="index"
            class=" history-item"
            style="position: relative" @longpress="onLongPress(index)">
        <view v-show="isShowCheck" :class="{ 'cuIcon-check': checkList[index], 'bg-gradual-awGreen': checkList[index] }"
              :style="{ border: !checkList[index] ? '#aaaaaa 1px solid' : 'none' }"
              class="round margin-right-sm flex justify-center align-center"
              style="width: 52rpx;height: 52rpx;font-size: 40rpx;border: #aaaaaa 1px solid"
              @click="checkList[index] = !checkList[index]">
        </view>
        <view class="left">
          <uv-image :src="item.imgURL" height="100%" mode="aspectFill" radius="10" width="100%"
                    @click="onClickImg(item.animalsId)">
            <template v-slot:loading>
              <view class="flex flex-column justify-center align-center padding-bottom-sm"
                    style="width: 100%;height: 100%;overflow: hidden">
                <uv-image :src="'/static/home-selected.png'" height="100%" mode="aspectFit" width="100%"></uv-image>
                <text v-if="!item.imgURL" class="text-gray text-sm flex justify-center align-center " style="">
                  图片暂缺
                </text>
              </view>
            </template>
          </uv-image>
        </view>
        <view class="right padding-sm flex flex-column justify-between" @click="onClickRight(item.animalsId, index)">
          <text class="text-black">{{ item.name }}</text>
          <text class="text-gray basis-xl" style="text-overflow: ellipsis;line-clamp: 2">{{
              item.desc.substring(0, 30)
            }}
          </text>
          <text class="text-gray text-sm" style="justify-self: flex-end">{{ item.timeDesc }}</text>
          <text class="cuIcon-moreandroid text-xs text-gray"
                style="position: absolute;right: 10rpx;bottom: 20rpx;font-size: large"
                @click.stop="onClickMore(item.id)"></text>
        </view>
      </view>

      <view class="text-gray text-df margin-top-lg"> 历史好像就到这里了(≧∇≦)ﾉ</view>
    </view>

    <!--   全部删除 -->
    <view v-show="isShowCheck" class="cu-bar bg-white tabbar border shop" style="position: fixed;bottom:0;width: 100%;">
      <view class="flex justify-start align-center">
        <view :class="{ 'cuIcon-check': isCheckedAll, 'bg-gradual-awGreen': isCheckedAll }"
              :style="{ border: !isCheckedAll ? '#aaaaaa 1px solid' : 'none' }"
              class="round margin-lr-sm flex justify-center align-center"
              style="width: 52rpx;height: 52rpx;font-size: 40rpx" @click="checkList?.fill(!isCheckedAll)">
        </view>
        <text class="text-lg text-gray margin-left-sx">全选</text>
      </view>
      <view class="action" style="width: auto">
        <text class="text-lg text-awGreen margin-right-xl" @click="onDeleteHistory">
          {{ isCheckedAll ? '删除全部' : '删除选中' }}
        </text>
      </view>
    </view>

  </view>

  <!--  弹出层-->
  <uni-popup ref="hPopup" type="center">
    <uni-popup-dialog :confirm-text="isCheckedAll ? '全部删除' : '删除选中'" content="确定要删除浏览历史吗？"
                      title="提示" type="info"
                      @confirm="onConfirmDelete">
    </uni-popup-dialog>
  </uni-popup>
</template>


<style lang="scss">
page{
  background: #FFFFFF;
}
.history {
  /* #ifdef H5 */
  background-color: #fff;
  /* #endif */
}

.history-list {
  padding:40px 0 20rpx 20rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  padding-top: 190rpx;
  /* #ifdef H5 */
  padding-top: 120rpx;
  /* #endif */
}

.history-item {
  width: 100%;
  height: 200rpx;
  //border-radius: 20rpx;
  margin: 10rpx;
  padding-bottom: 5px;
  border-bottom: #cccccc 1px solid;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  background: #FFFFFF;

  .left {
    flex: 3;
    height: 100%;
    border-radius: 20rpx;
  }

  .right {
    flex: 5;
    height: 100%;
  }

}
</style>
